package com.study.manage.mvc.teach;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.AlbumRepository;
import com.study.manage.dal.TagRepository;
import com.study.manage.dal.UserDetailRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.dal.VerifyRepository;
import com.study.manage.domain.Album;
import com.study.manage.domain.Tag;
import com.study.manage.domain.User;
import com.study.manage.domain.UserDetail;
import com.study.manage.domain.Verify;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.domain.enumm.VerifyState;
import com.study.manage.domain.enumm.VerifyType;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.SessionUser;
import com.study.manage.dto.UserDetailDto;
import com.study.manage.mvc.common.UploadController;

@Controller
@RequestMapping("/teach")
public class TeachController extends UploadController {

    @Autowired
    private TagRepository tagRepository;
    @Autowired
    private UserDetailRepository userDetailRepository;
    @Autowired
    private AlbumRepository albumRepository;
    @Autowired
    private VerifyRepository verifyRepository;
    @Autowired
    private UserRepository userRepository;


    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public String detail(HttpServletRequest request, ModelMap model, HttpServletResponse response) {
//        SessionUser user = this.getCurrentUser(request);
    	SessionUser user = (SessionUser) session.getAttribute("user");

        List<Tag> tags = tagRepository.findByStateOrderBySquenAsc(LiveDieState.LIVE);
        model.put("tags", jsonMapper.toJson(tags));

        Page<Album> albums = albumRepository.findByStateAndUserIdOrderByCreatedAtDesc(
                LiveDieState.LIVE, user.getId(), new PageRequest(0, 11));
        model.put("albums", albums);

        UserDetail userDetail = userDetailRepository.findByUserId(user.getId());
        model.put("userDetail", userDetail == null ? new UserDetail() : userDetail);

        User user2 = userRepository.findOne(user.getId());
        model.put("user", user2 == null ? new User() : user2);
        model.put("qiniuUrl", qiniuUrl);
        return "teach/detail";
    }

    @ResponseBody
    @RequestMapping(path = "detail", method = RequestMethod.POST)
    public AjaxResponse detail(UserDetailDto userDetailDto, HttpServletRequest request,
            HttpServletResponse response) {
        AjaxResponse ajaxResponse = new AjaxResponse(true);
        try {
//            SessionUser user = this.getCurrentUser(request);
            SessionUser user = (SessionUser) session.getAttribute("user");
            UserDetail detail = userDetailRepository.findByUserId(user.getId());

            if (userDetailDto.getRealName() == null) {
                if (userDetailDto.getTeachings() == null) {
                    return ajaxResponse.setMsg("教学科目必需选择");
                }
                detail.teachings = jsonMapper.toJson(userDetailDto.getTeachings());
                detail.jiaoling = userDetailDto.getJiaoling();
                detail.description = userDetailDto.getDescription();
                detail.achievement = userDetailDto.getAchievement();
                detail.experiences = "[]";
                detail.tese = "";
                if (userDetailDto.getBeginMonth() == null) {
                    return ajaxResponse.setMsg("经历不能为空");
                }
                List<Map<String, Object>> list = new ArrayList<>();
                for (int i = 0; i < userDetailDto.getBeginMonth().length; i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("begin", new StringBuilder(userDetailDto.getBeginYear()[i].toString())
                            .append("-").append(userDetailDto.getBeginMonth()[i]));
                    map.put("end", new StringBuilder(userDetailDto.getEndYear()[i].toString())
                            .append("-").append(userDetailDto.getEndMonth()[i]));
                    map.put("desc", userDetailDto.getDesc()[i]);
                    list.add(map);
                }
                detail.experiences = jsonMapper.toJson(list);

                if (userDetailDto.getTeses() != null) {
                    String te = "";
                    for (String tese : userDetailDto.getTeses()) {
                        te += "," + tese;
                    }
                    detail.tese = te.replaceFirst(",", "");;
                }
                if (userDetailDto.getXcImgs() != null) {
                    for (String xc : userDetailDto.getXcImgs()) {
                        Album album = new Album();
                        album.state = LiveDieState.LIVE;
                        album.userId = user.getId();
                        album.url = xc;
                        albumRepository.save(album);
                    }
                }
            } else {
                detail.realName = userDetailDto.getRealName();
                detail.autograph = userDetailDto.getAutograph();
                detail.addressProvince = userDetailDto.getAddressProvince();
                detail.addressCity = userDetailDto.getAddressCity();
                detail.addressDistrict = userDetailDto.getAddressDistrict();
                detail.addressDetail = userDetailDto.getAddressDetail();
                detail.idNumber = userDetailDto.getIdNumber();
                detail.gender = userDetailDto.getGender();
                detail.birthYear = userDetailDto.getBirthYear();
                detail.birthMonth = userDetailDto.getBirthMonth();
                detail.birthDay = userDetailDto.getBirthDay();
            }
            userDetailRepository.save(detail);
        } catch (Exception e) {
            logger.error("系统异常了 T_T ", e);
            ajaxResponse.setMsg(e.getMessage());
        }
        return ajaxResponse;
    }

    @RequestMapping(path = "renzheng", method = RequestMethod.GET)
    public String renzheng(HttpServletRequest request, ModelMap model) {
        String ret = "teach/renzheng";
        try {
//            SessionUser user = this.getCurrentUser(request);
        	 SessionUser user = (SessionUser) session.getAttribute("user");
            Verify verify = verifyRepository.findByUserIdAndTypeAndState(user.getId(),
                    VerifyType.TeacherPersonID, VerifyState.LIVE);
            if (verify != null) {
                ret = "teach/detail";
            }
            List<Tag> tags = tagRepository.findByStateOrderBySquenAsc(LiveDieState.LIVE);
            model.put("tags", jsonMapper.toJson(tags));

            Page<Album> albums = albumRepository.findByStateAndUserIdOrderByCreatedAtDesc(
                    LiveDieState.LIVE, user.getId(), new PageRequest(0, 11));
            model.put("albums", albums);

            UserDetail userDetail = userDetailRepository.findByUserId(user.getId());
            model.put("userDetail", userDetail == null ? new UserDetail() : userDetail);

            User user2 = userRepository.findOne(user.getId());
            model.put("user", user2 == null ? new User() : user2);
        } catch (Exception e) {
        }
        model.put("qiniuUrl", qiniuUrl);
        return ret;
    }

    @ResponseBody
    @RequestMapping(path = "renzheng", method = RequestMethod.POST)
    public AjaxResponse renzheng(UserDetailDto userDetailDto, HttpServletRequest request,
            HttpServletResponse response) {
        AjaxResponse ajaxResponse = new AjaxResponse(true);
        try {
//            SessionUser user = this.getCurrentUser(request);
            SessionUser user = (SessionUser) session.getAttribute("user");
            UserDetail detail = userDetailRepository.findByUserId(user.getId());
            if (detail == null)
                detail = new UserDetail();
            detail.userId = user.getId();
            detail.realName = userDetailDto.getRealName();
            detail.jiaoling = userDetailDto.getJiaoling();
            detail.addressProvince = userDetailDto.getAddressProvince();
            detail.addressCity = userDetailDto.getAddressCity();
            detail.addressDistrict = userDetailDto.getAddressDistrict();
            detail.addressDetail = userDetailDto.getAddressDetail();
            detail.idNumber = userDetailDto.getIdNumber();
            detail.description = userDetailDto.getDescription();
            detail.achievement = userDetailDto.getAchievement();
            detail.autograph = userDetailDto.getAutograph();
            if (userDetailDto.getTeachings() == null) {
                return ajaxResponse.setMsg("教学科目必需选择");
            }
            detail.teachings = jsonMapper.toJson(userDetailDto.getTeachings());
            detail.experiences = "[]";
            detail.tese = "";
            if (userDetailDto.getBeginMonth() == null) {
                return ajaxResponse.setMsg("经历不能为空");
            }
            List<Map<String, Object>> list = new ArrayList<>();
            for (int i = 0; i < userDetailDto.getBeginMonth().length; i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("begin", new StringBuilder(userDetailDto.getBeginYear()[i].toString())
                        .append("-").append(userDetailDto.getBeginMonth()[i]));
                map.put("end", new StringBuilder(userDetailDto.getEndYear()[i].toString())
                        .append("-").append(userDetailDto.getEndMonth()[i]));
                map.put("desc", userDetailDto.getDesc()[i]);
                list.add(map);
            }
            detail.experiences = jsonMapper.toJson(list);

            if (userDetailDto.getTeses() != null) {
                String te = "";
                for (String tese : userDetailDto.getTeses()) {
                    te += "," + tese;
                }
                detail.tese = te.replaceFirst(",", "");;
            }

            if (userDetailDto.getXcImgs() != null) {
                for (String xc : userDetailDto.getXcImgs()) {
                    Album album = new Album();
                    album.state = LiveDieState.LIVE;
                    album.userId = user.getId();
                    album.url = xc;
                    albumRepository.save(album);
                }
            }
            userDetailRepository.save(detail);

            Verify verify = verifyRepository.findByUserIdAndTypeAndState(user.getId(),
                    VerifyType.TeacherPersonID, VerifyState.Waiting);
            if (verify == null) {
                verify = new Verify();
            }
            verify.state = VerifyState.Waiting;
            verify.type = VerifyType.TeacherPersonID;
            verify.userId = user.getId();
            verifyRepository.save(verify);
        } catch (Exception e) {
            logger.error("系统异常了 T_T ", e);
            ajaxResponse.setMsg(e.getMessage());
        }
        return ajaxResponse;
    }

    @ResponseBody
    @RequestMapping(path = "renzheng/delxc", method = RequestMethod.POST)
    public AjaxResponse delxc(Long id, HttpServletRequest request, HttpServletResponse response) {
        AjaxResponse ajaxResponse = new AjaxResponse(true);
        try {
//            this.getCurrentUser(request);
            Album album = albumRepository.findOne(id);
            album.state = LiveDieState.DIE;
            albumRepository.save(album);
        } catch (Exception e) {
            logger.error("系统异常了 T_T ", e);
            ajaxResponse.setMsg(e.getMessage());
        }
        return ajaxResponse;
    }


    @ResponseBody
    @RequestMapping(path = "renzheng/upload", method = RequestMethod.POST)
    public AjaxResponse renzhengUpload(Integer type, HttpServletRequest request,
            HttpServletResponse response) {
        AjaxResponse ajaxResponse = new AjaxResponse(true);
        try {
            String tx = "";
//            SessionUser user = this.getCurrentUser(request);
            SessionUser user = (SessionUser) session.getAttribute("user");
            if (type == 1) {
                tx = new StringBuilder("pic_avatar_").append(user.getNumber().toString())
                        .append(".jpg").toString();
            } else if (type == 2) {
                tx = new StringBuilder("pic_id_").append(user.getNumber().toString())
                        .append("_0.jpg").toString();
            } else if (type == 3) {
                tx = new StringBuilder("pic_id_").append(user.getNumber().toString())
                        .append("_1.jpg").toString();
            } else if (type == 4) {
                tx = new StringBuilder("pic_id_").append(user.getNumber().toString())
                        .append("_2.jpg").toString();
            } else if (type == 5) {
                return ajaxResponse.setObj(uploadFiles(request, response));
            }
            Map<String, String> json = this.uploadFile(tx, request, response);
            ajaxResponse.setObj(json);
        } catch (Exception e) {
            logger.error("系统异常了 T_T ", e);
            ajaxResponse.setMsg(e.getMessage());
        }
        return ajaxResponse;
    }


}
